﻿@inject LocalVehiclesStore LocalVehiclesStore
@inject IStringLocalizer<App> Localize

@if (isSynchronizing)
{
    <span>@Localize["Updating..."]</span>
}
else if (lastSyncFailed)
{
    <span>@Localize["Could not sync. Unsent edits:"] @outstandingLocalEdits</span>
    <a class="toolbar-item toolbar-item-end toolbar-item-bg" @onclick="Synchronize">@Localize["Retry"]</a>
}
else
{
    <span>@Localize["Last updated:"] @GetLastUpdatedText()</span>
    <a class="toolbar-item toolbar-item-end" @onclick="Synchronize">@Localize["Update"]</a>
}

@code {
    bool isSynchronizing;
    DateTime? lastUpdated;
    int outstandingLocalEdits;
    bool lastSyncFailed;

    protected override async Task OnInitializedAsync()
    {
        await Synchronize();
    }

    async Task Synchronize()
    {
        isSynchronizing = true;
        lastSyncFailed = false;

        try
        {
            await LocalVehiclesStore.SynchronizeAsync();
        }
        catch (Exception ex)
        {
            lastSyncFailed = true;
            Console.WriteLine(ex);
        }
        finally
        {
            // Even if we weren't able to reach the server, we can update status based on local data
            lastUpdated = await LocalVehiclesStore.GetLastUpdateDateAsync();
            outstandingLocalEdits = (await LocalVehiclesStore.GetOutstandingLocalEditsAsync()).Length;
        }

        isSynchronizing = false;
    }

    string GetLastUpdatedText()
    {
        if (lastUpdated.HasValue)
        {
            return lastUpdated.Value.Date == DateTime.Now.Date
                ? lastUpdated.Value.ToLocalTime().ToShortTimeString()
                : lastUpdated.Value.ToLocalTime().ToShortDateString();
        }
        else
        {
            return Localize["Never"];
        }
    }
}
